package cn.bdqn.sptparent.web.controller;


import cn.bdqn.sptparent.common.util.JSONUtil;
import cn.bdqn.sptparent.common.util.RedisUtil;
import cn.bdqn.sptparent.domain.Result;
import cn.bdqn.sptparent.domain.po.Productimage;
import cn.bdqn.sptparent.domain.po.User;
import cn.bdqn.sptparent.service.ProductimageService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lhl
 * @since 2023-05-17
 */
@RestController
@CrossOrigin
@RequestMapping("/productimage")
public class ProductimageController {
    @Resource
    private ProductimageService productimageService;

    @Resource
    private RedisUtil redisUtil;

    @GetMapping("/top")
    public Result top(
            @RequestParam(value = "size",required = false,defaultValue = "5") long size,HttpServletRequest request){
        String key = "productimage:top:list";
        if(redisUtil.hasKey(key)){
            String str = redisUtil.get(key).toString();
            List<Productimage> list = (List<Productimage>) JSONObject.parseObject(str,List.class);
            return Result.ok().data(list);
        }else{
            QueryWrapper<Productimage> queryWrapper = new QueryWrapper<Productimage>();
            queryWrapper.lambda().orderByAsc(Productimage::getProductimageId);
            List<Productimage> list = productimageService.page(new Page<Productimage>(1,size),queryWrapper).getRecords();
            list.forEach(productimage -> productimage.setProductimageSrc(
                    request.getProtocol().replace("/1.1","") + "://" + request.getServerName()+":"+request.getServerPort()
                            +"/static/images/item/productSinglePicture/"
                            +productimage.getProductimageSrc()));
            redisUtil.set(key, list);
            return Result.ok().data(list);
        }
    }
}
